<?php
/**
 * Data Model
 *
 * @property Data $ParentData
 * @property Data $ChildData
 */
class WxPay extends WechatAppModel {

/**
 * Use table
 *
 * @var mixed False or table name
 */
	public $useTable = false;

	public function getJsApi($open_id = false,$param = array(),$type = 'JSAPI'){
	    App::import('Vendor','Wechat.WxPayApi',array('file'=>'wxpay'.DS.'WxPay.Api.php'));
	    $input = new WxPayUnifiedOrder();
	    $input->SetBody($param['body']);
	    $input->SetAttach($param['attach']);
	    $input->SetOut_trade_no($param['out_trade_no']);
	    $input->SetTotal_fee($param['fee']*100);
	    $input->SetTime_start(date("YmdHis"));
	    $input->SetTime_expire(date("YmdHis", time() + 6000));
	    $input->SetGoods_tag($param['tag']);
	    $input->SetNotify_url($param['notify']);
	    $input->SetTrade_type($type);
	    $input->SetOpenid($open_id);
	    $order = WxPayApi::unifiedOrder($input);
	    if((isset($order['return_code']) && $order['return_code'] == 'FAIL') 
	        ||(isset($order['result_code']) && $order['result_code'] == 'FAIL')){
	        return array(
	            'return_code'=>'FAIL',
	            'return_msg'=>isset($order['err_code_des'])?$order['err_code_des']:$order['return_msg']
	        );
	    }
	    return $this->GetJsApiParameters($order,$type);
	}
	
	/**
	 *
	 * 获取jsapi支付的参数
	 * @param array $UnifiedOrderResult 统一支付接口返回的数据
	 * @throws WxPayException
	 *
	 * @return json数据，可直接填入js函数作为参数
	 */
	public function GetJsApiParameters($UnifiedOrderResult,$type = 'JSAPI')
	{
	    if(!array_key_exists("appid", $UnifiedOrderResult)
	        || !array_key_exists("prepay_id", $UnifiedOrderResult)
	        || $UnifiedOrderResult['prepay_id'] == "")
	    {
	        throw new WxPayException("参数错误");
	    }
	    $jsapi = new WxPayJsApiPay();
	    $jsapi->SetAppid($UnifiedOrderResult["appid"]);
	    $timeStamp = time();
	    $jsapi->SetTimeStamp($timeStamp);
	    $jsapi->SetNonceStr(WxPayApi::getNonceStr());
	    if($type == 'JSAPI'){
		    $jsapi->SetPackage("prepay_id=" . $UnifiedOrderResult['prepay_id']);
	    }else{
	    	$jsapi->SetPackage("prepayId=" . $UnifiedOrderResult['prepay_id']);
	    }
	    $jsapi->SetSignType("MD5");
	    $jsapi->SetPaySign($jsapi->MakeSign());
	    $last = $jsapi->GetValues();
	    $last['timestamp'] = $last['timeStamp'];
	    unset($last['timeStamp']);
	    $parameters = $last;
	    return $parameters;
	}
}
